<template>
  <div class="settings-page">
    <el-breadcrumb separator="/" style="margin-bottom: 16px;">
      <el-breadcrumb-item to="/home">{{ $t('menu.home') }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t('menu.settings') }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="settings-card">
      <!-- 页面标题 -->
      <div class="settings-header">
      <el-icon class="header-icon"><Setting /></el-icon>
      <h2 class="header-title">{{ $t('settings.title') }}</h2>
      </div>

    <!-- 主要内容区域 -->
    <el-scrollbar class="settings-scrollbar">
      <div class="settings-content">
        <!-- 基本设置分组 -->
        <div class="settings-group">
          <div class="group-header">
            <el-icon class="group-icon"><Tools /></el-icon>
            <h3 class="group-title">{{ $t('settings.basicSettings') }}</h3>
          </div>

          <div class="group-body">
            <!-- 选项设置项 -->
            <div class="setting-item">
              <div class="setting-label">
                <span class="label-text">{{ $t('settings.displayMode') }}</span>
                <span class="label-desc">{{ $t('settings.displayModeDesc') }}</span>
              </div>
              <div class="setting-control">
                <el-radio-group v-model="radio" size="large">
                  <el-radio label="option1" class="radio-custom">
                    <div class="radio-content">
                      <el-icon><Sunny /></el-icon>
                      <span>{{ $t('settings.lightMode') }}</span>
                    </div>
                  </el-radio>
                  <el-radio label="option2" class="radio-custom">
                    <div class="radio-content">
                      <el-icon><Moon /></el-icon>
                      <span>{{ $t('settings.darkMode') }}</span>
                    </div>
                  </el-radio>
                </el-radio-group>
              </div>
            </div>

            <!-- 开关设置项 -->
            <div class="setting-item">
              <div class="setting-label">
                <span class="label-text">{{ $t('settings.notifications') }}</span>
                <span class="label-desc">{{ $t('settings.notificationsDesc') }}</span>
              </div>
              <div class="setting-control">
                <el-switch
                  v-model="switchValue"
                  :active-text="$t('settings.enabled')"
                  :inactive-text="$t('settings.disabled')"
                  active-color="#409EFF"
                  inactive-color="#DCDFE6"
                  class="switch-custom"
                ></el-switch>
              </div>
            </div>

            <!-- 下拉选择设置项 -->
            <div class="setting-item">
              <div class="setting-label">
                <span class="label-text">{{ $t('settings.language') }}</span>
                <span class="label-desc">{{ $t('settings.languageDesc') }}</span>
              </div>
              <div class="setting-control">
                <el-select
                  v-model="selectedLanguage"
                  :placeholder="$t('settings.selectLanguage')"
                  size="large"
                  class="select-custom"
                >
                  <el-option 
                    v-for="item in localeStore.supportedLocales" 
                    :key="item.value"
                    :label="item.label" 
                    :value="item.value"
                  />
                </el-select>
              </div>
            </div>

            <!-- 滑块设置项 -->
            <div class="setting-item">
              <div class="setting-label">
                <span class="label-text">{{ $t('settings.fontSize') }}</span>
                <span class="label-desc">{{ $t('settings.fontSizeDesc') }}</span>
              </div>
              <div class="setting-control">
                <el-slider
                  v-model="fontSize"
                  :min="12"
                  :max="18"
                  :step="1"
                  show-input
                  size="large"
                  class="slider-custom"
                ></el-slider>
              </div>
            </div>
          </div>
        </div>

        <!-- 安全设置分组 -->
        <div class="settings-group">
          <div class="group-header">
            <el-icon class="group-icon"><Lock /></el-icon>
            <h3 class="group-title">{{ $t('settings.securitySettings') }}</h3>
          </div>

          <div class="group-body">
            <!-- 安全相关设置项 -->
            <div class="setting-item">
              <div class="setting-label">
                <span class="label-text">{{ $t('settings.loginVerification') }}</span>
                <span class="label-desc">{{ $t('settings.loginVerificationDesc') }}</span>
              </div>
              <div class="setting-control">
                <el-switch
                  v-model="loginVerification"
                  :active-text="$t('settings.enabled')"
                  :inactive-text="$t('settings.disabled')"
                  active-color="#409EFF"
                  inactive-color="#DCDFE6"
                  class="switch-custom"
                ></el-switch>
              </div>
            </div>

            <div class="setting-item">
              <div class="setting-label">
                <span class="label-text">{{ $t('settings.changePassword') }}</span>
                <span class="label-desc">{{ $t('settings.changePasswordDesc') }}</span>
              </div>
              <div class="setting-control">
                <el-button
                  type="text"
                  class="text-button"
                  @click="handleChangePassword"
                >
                  <span>{{ $t('settings.changePassword') }}</span>
                  <el-icon class="button-icon"><ArrowRight /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="settings-actions">
          <el-button
            type="primary"
            @click="handleSaveSettings"
            class="btn-save"
            size="large"
          >
            <el-icon><Check /></el-icon>
            <span>{{ $t('settings.saveSettings') }}</span>
          </el-button>
          <el-button
            @click="handleResetSettings"
            class="btn-reset"
            size="large"
          >
            <el-icon><RefreshLeft /></el-icon>
            <span>{{ $t('settings.resetSettings') }}</span>
          </el-button>
        </div>
      </div>
    </el-scrollbar>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useThemeStore } from '@/stores/theme';
import { useNotificationStore } from '@/stores/notification';
import { useLocaleStore } from '@/stores/locale';
import settingsApi from '@/api/settings';

// Store
const themeStore = useThemeStore();
const notificationStore = useNotificationStore();
const localeStore = useLocaleStore();
const { locale, t } = useI18n();

// 状态管理
const radio = ref('option1');
const switchValue = ref(notificationStore.enabled); // 从notificationStore初始化
const selectedLanguage = ref(localeStore.currentLocale); // 从localeStore初始化
const fontSize = ref(14);
const loginVerification = ref(true);
const loading = ref(false);
const isSyncingFromStore = ref(false); // 标志位：是否正在从Store同步

// 保存原始值用于重置
const originalSettings = reactive({
  radio: 'option1',
  switchValue: false,
  selectedLanguage: 'zh-CN',
  fontSize: 14,
  loginVerification: true
});

// 监听显示模式变化，实时切换主题
watch(radio, (newValue) => {
  // 如果是从Store同步的，不触发applyTheme（避免重复提示）
  if (!isSyncingFromStore.value) {
    applyTheme(newValue);
  }
}, { immediate: false });

// 监听通知开关变化，同步到notificationStore
watch(switchValue, (newValue) => {
  notificationStore.setEnabled(newValue);
  if (!isSyncingFromStore.value) {
    ElMessage.success(newValue ? t('settings.notificationsEnabled') : t('settings.notificationsDisabled'));
  }
}, { immediate: false });

// 监听语言选择变化，同步到localeStore和i18n
watch(selectedLanguage, (newValue) => {
  if (!isSyncingFromStore.value) {
    localeStore.setLocale(newValue);
    locale.value = newValue;
    ElMessage.success(t('settings.languageChanged'));
  }
}, { immediate: false });

// 监听themeStore的变化，同步到radio（当用户在Header切换主题时）
watch(() => themeStore.isDark, (isDark) => {
  const expectedRadio = isDark ? 'option2' : 'option1';
  // 只有当radio值与实际主题不一致时才更新（避免循环触发）
  if (radio.value !== expectedRadio) {
    isSyncingFromStore.value = true; // 标记为同步状态
    radio.value = expectedRadio;
    // 下一个tick后重置标志位
    setTimeout(() => {
      isSyncingFromStore.value = false;
    }, 0);
  }
});

// 应用主题（使用全局主题Store）
const applyTheme = (mode) => {
  const theme = mode === 'option2' ? 'dark' : 'light';
  themeStore.setTheme(theme);
  ElMessage.success(mode === 'option2' ? t('settings.themeSwitchedToDark') : t('settings.themeSwitchedToLight'));
};

// 组件挂载时加载设置
onMounted(async () => {
  await loadSettings();
});

// 加载用户设置
const loadSettings = async () => {
  try {
    loading.value = true;
    const settings = await settingsApi.getSettings();
    
    // ⚠️ 重要：优先使用themeStore的真实状态，而不是存储的设置
    // 因为用户可能在Header切换了主题，但还没有点击"保存设置"
    const currentTheme = themeStore.isDark ? 'option2' : 'option1';
    
    // 更新界面值（设置同步标志，避免触发watch）
    isSyncingFromStore.value = true;
    radio.value = currentTheme;  // 使用themeStore的真实状态
    switchValue.value = notificationStore.enabled;  // 使用notificationStore的真实状态
    selectedLanguage.value = localeStore.currentLocale;  // 使用localeStore的真实状态
    fontSize.value = settings.fontSize || 14;
    loginVerification.value = settings.loginVerification !== undefined ? settings.loginVerification : true;
    
    // 更新原始值
    originalSettings.radio = radio.value;
    originalSettings.switchValue = switchValue.value;
    originalSettings.selectedLanguage = selectedLanguage.value;
    originalSettings.fontSize = fontSize.value;
    originalSettings.loginVerification = loginVerification.value;
    
    // 重置同步标志
    setTimeout(() => {
      isSyncingFromStore.value = false;
    }, 0);
    
  } catch (error) {
    ElMessage.error(t('settings.saveFailed') + ': ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 保存设置
const handleSaveSettings = async () => {
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: t('settings.savingSettings'),
    background: 'rgba(255, 255, 255, 0.7)'
  });

  try {
    const settings = {
      displayMode: radio.value,
      notifications: switchValue.value,
      language: selectedLanguage.value,
      fontSize: fontSize.value,
      loginVerification: loginVerification.value
    };
    
    await settingsApi.saveSettings(settings);
    
    // 更新原始值
    originalSettings.radio = radio.value;
    originalSettings.switchValue = switchValue.value;
    originalSettings.selectedLanguage = selectedLanguage.value;
    originalSettings.fontSize = fontSize.value;
    originalSettings.loginVerification = loginVerification.value;
    
    ElMessage.success(t('settings.saveSuccess'));
  } catch (error) {
    ElMessage.error(t('settings.saveFailed') + ': ' + error.message);
  } finally {
    loadingInstance.close();
  }
};

// 重置设置
const handleResetSettings = async () => {
  try {
    const loadingInstance = ElLoading.service({
      text: t('settings.resettingSettings'),
      background: 'rgba(255, 255, 255, 0.7)'
    });
    
    const defaultSettings = await settingsApi.resetSettings();
    
    // 重置时设置同步标志，避免触发watch显示切换主题的提示
    isSyncingFromStore.value = true;
    
    // 更新界面值
    radio.value = defaultSettings.displayMode || 'option1';
    switchValue.value = defaultSettings.notifications || false;
    selectedLanguage.value = defaultSettings.language || 'zh-CN';
    fontSize.value = defaultSettings.fontSize || 14;
    loginVerification.value = defaultSettings.loginVerification !== undefined ? defaultSettings.loginVerification : true;
    
    // 重置主题到浅色模式（默认）
    themeStore.setTheme('light');
    
    // 重置通知到关闭状态（默认）
    notificationStore.setEnabled(false);
    
    // 重置语言到简体中文（默认）
    localeStore.setLocale('zh-CN');
    locale.value = 'zh-CN';
    
    // 重置同步标志
    setTimeout(() => {
      isSyncingFromStore.value = false;
    }, 0);
    
    // 更新原始值
    originalSettings.radio = radio.value;
    originalSettings.switchValue = switchValue.value;
    originalSettings.selectedLanguage = selectedLanguage.value;
    originalSettings.fontSize = fontSize.value;
    originalSettings.loginVerification = loginVerification.value;
    
    loadingInstance.close();
    ElMessage.success(t('settings.resetSuccess'));
  } catch (error) {
    ElMessage.error(t('settings.resetFailed') + ': ' + error.message);
  }
};

// 修改密码
const handleChangePassword = () => {
  ElMessage.info(t('settings.changePasswordDesc'));
  // 实际应用中这里会跳转到密码修改页面
};
</script>

<style scoped src="@/styles/Settings.scss"></style>
